package com.zj.service;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.zj.restApi.ProductApi;
import com.zj.web.bean.BannerDTO;
import com.zj.web.bean.ProductDTO;
import com.zj.web.bean.RedPacketActivityDTO;
import com.zj.web.bean.ResponseResult;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.ObjectMapper; // Add this import at the top of the file
import java.util.ArrayList;
import java.util.List;

@Service
@Log
public class ProductToolService {

    @Autowired
    private ProductApi productApi;


    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class ProductSearchResponse {
        @JsonProperty("data")
        public List<ProductDTO> data;
    }

    @Tool("搜索特价商品信息，用户会提供商品状态，你需要根据商品状态搜索特价商品")
    public String searchSpecialProduct(@P("商品状态") Integer productStatus) {
        try {
            log.info("开始搜索特价商品，状态: " + productStatus);

            // 调用商品服务的特价商品接口
            ResponseEntity<ResponseResult> responseEntity = productApi.specialProducts(productStatus);

            if (responseEntity.getStatusCode() != HttpStatus.OK || responseEntity.getBody() == null) {
                return "抱歉，商品服务暂时不可用，请稍后重试。";
            }

            ResponseResult responseResult = responseEntity.getBody();
            log.info("商品服务返回: " + responseResult);

            if (responseResult.getCode() != 1) {
                return "抱歉，查询特价商品失败: " + responseResult.getMsg();
            }

//            // 获取商品数据 - 原代码直接转换为List<ProductDTO>导致类型转换异常
//            // List<ProductDTO> products = (List<ProductDTO>) responseResult.getData();
//            List<ProductDTO> products = (List<ProductDTO>) responseResult.getData();
            List<?> dataList = (List<?>) responseResult.getData();
            List<ProductDTO> products = new ArrayList<>();
            ObjectMapper objectMapper = new ObjectMapper();
            for (Object item : dataList) {
                // 将LinkedHashMap转换为ProductDTO对象
                ProductDTO product = objectMapper.convertValue(item, ProductDTO.class);
                products.add(product);
            }
            if (products == null || products.isEmpty()) {
                return "目前没有特价商品，请关注后续促销活动。";
            }

            // 构建商品信息响应
            StringBuilder result = new StringBuilder();
            result.append("为您找到以下特价商品：\n\n");

            for (ProductDTO product : products) {
                result.append(String.format("""
                    🏷️ 商品名称：%s
                    🔢 商品ID：%d
                    💰 价格：%.2f元
                    📝 详细描述：%s
                    🏷️ 分类ID：%s
                    🌟 图片链接：%s
                    📊 状态：%s
                    🏷️ 分类名称：%s
                    --------------------
                    """,
                        product.getProductName() != null ? product.getProductName() : "未知",
                        product.getProductId() != null ? product.getProductId() : 0,
                        product.getPrice() != null ? product.getPrice() : 0.0,
                        product.getDescription() != null ? product.getDescription() : "暂无描述",
                        product.getCategoryId() != null ? product.getCategoryId() : "未知",
                        product.getProductImg() != null ? product.getProductImg() : "暂无图片",
                        getStatusText(product.getProductStatus()),
                        product.getCategoryName() != null ? product.getCategoryName().toString() : "未知分类"
                ));
            }

            return result.toString();

        } catch (Exception e) {
            log.severe("查询特价商品时出现错误: " + e.getMessage());
            e.printStackTrace();
            return "查询特价商品时出现系统错误，请稍后重试。";
        }
    }

    @Tool("根据商品ID查询商品详细信息,用户会提供商品ID,你需要根据商品ID查询商品详细信息")
    public String getProductDetailById(@P("商品ID") Long productId) {
        try {
            log.info("根据ID查询商品详情，ID: " + productId);

            ResponseEntity<ResponseResult> responseEntity = productApi.getProductDetailById(productId);

            if (responseEntity.getStatusCode() != HttpStatus.OK || responseEntity.getBody() == null) {
                return "抱歉，商品服务暂时不可用，请稍后重试。";
            }

            ResponseResult responseResult = responseEntity.getBody();

            if (responseResult.getCode() != 1) {
                return "抱歉，没有找到ID为 " + productId + " 的商品。";
            }

            // 修复LinkedHashMap到ProductDTO的转换问题
            // ProductDTO product = (ProductDTO) responseResult.getData();
            Object data = responseResult.getData();
            ObjectMapper objectMapper = new ObjectMapper();
            ProductDTO product = objectMapper.convertValue(data, ProductDTO.class);

            if (product == null) {
                return "抱歉，商品信息为空。";
            }

            return String.format("""
                🎯 商品详情信息：
                
                🏷️ 商品名称：%s
                🔢 商品ID：%d
                💰 价格：%.2f元
                📝 详细描述：%s
                🏷️ 分类ID：%s
                🌟 图片链接：%s
                📊 状态：%s
                🏷️ 分类名称：%s
                """,
                    product.getProductName() != null ? product.getProductName() : "未知",
                    product.getProductId() != null ? product.getProductId() : 0,
                    product.getPrice() != null ? product.getPrice() : 0.0,
                    product.getDescription() != null ? product.getDescription() : "暂无详细描述",
                    product.getCategoryId() != null ? product.getCategoryId() : "未知",
                    product.getProductImg() != null ? product.getProductImg() : "暂无图片",
                    getStatusText(product.getProductStatus()),
                    product.getCategoryName() != null ? product.getCategoryName().toString() : "未知分类"
            );

        } catch (Exception e) {
            log.severe("查询商品详情时出现错误: " + e.getMessage());
            e.printStackTrace();
            return "查询商品详情时出现系统错误，请稍后重试。";
        }
    }

    @Tool("根据分类ID查询该分类下的所有商品,用户会提供分类ID,你需要根据分类ID查询该分类下的所有商品")
    public String getProductsByCategory(@P("分类ID") Long categoryId) {
        try {
            log.info("根据分类查询商品，分类ID: " + categoryId);

            ResponseEntity<ResponseResult> responseEntity = productApi.getProductsByCategoryId(categoryId);

            if (responseEntity.getStatusCode() != HttpStatus.OK || responseEntity.getBody() == null) {
                return "抱歉，商品服务暂时不可用，请稍后重试。";
            }

            ResponseResult responseResult = responseEntity.getBody();

            if (responseResult.getCode() != 1) {
                return "抱歉，查询分类商品失败: " + responseResult.getMsg();
            }

            List<?> dataList = (List<?>) responseResult.getData();
            List<ProductDTO> products = new ArrayList<>();
            ObjectMapper objectMapper = new ObjectMapper();
            for (Object item : dataList) {
                // 将LinkedHashMap转换为ProductDTO对象
                ProductDTO product = objectMapper.convertValue(item, ProductDTO.class);
                products.add(product);
            }

            if (products == null || products.isEmpty()) {
                return "该分类下暂时没有商品。";
            }

            StringBuilder result = new StringBuilder();
            result.append("该分类下的商品列表：\n\n");

            for (ProductDTO product : products) {
                result.append(String.format("""
                    🎯 商品详情信息：
                
                🏷️ 商品名称：%s
                🔢 商品ID：%d
                💰 价格：%.2f元
                📝 详细描述：%s
                📊 状态：%s              
                    """,
                        product.getProductName() != null ? product.getProductName() : "未知商品",
                        product.getProductId() != null ? product.getProductId() : 0,
                        product.getPrice() != null ? product.getPrice() : 0.0,
                        product.getDescription() != null ? product.getDescription() : "暂无详细描述",
                        getStatusText(product.getProductStatus())
                ));
            }

            return result.toString();

        } catch (Exception e) {
            log.severe("查询分类商品时出现错误: " + e.getMessage());
            e.printStackTrace();
            return "查询分类商品时出现系统错误，请稍后重试。";
        }
    }

    @Tool("根据商品状态查询所有商品")
    public String getAllProductsByStatus(@P("商品状态") Integer productStatus) {
        try {
            log.info("根据状态查询所有商品，状态: " + productStatus);

            ResponseEntity<ResponseResult> responseEntity = productApi.allProducts(productStatus);

            if (responseEntity.getStatusCode() != HttpStatus.OK || responseEntity.getBody() == null) {
                return "抱歉，商品服务暂时不可用，请稍后重试。";
            }

            ResponseResult responseResult = responseEntity.getBody();

            if (responseResult.getCode() != 1) {
                return "抱歉，查询商品失败: " + responseResult.getMsg();
            }

            List<?> dataList = (List<?>) responseResult.getData();
            List<ProductDTO> products = new ArrayList<>();
            ObjectMapper objectMapper = new ObjectMapper();
            for (Object item : dataList) {
                // 将LinkedHashMap转换为ProductDTO对象
                ProductDTO product = objectMapper.convertValue(item, ProductDTO.class);
                products.add(product);
            }

            if (products == null || products.isEmpty()) {
                return "目前没有" + getStatusText(productStatus) + "的商品。";
            }

            StringBuilder result = new StringBuilder();
            result.append("为您找到以下").append(getStatusText(productStatus)).append("商品：\n\n");

            for (ProductDTO product : products) {
                result.append(String.format("""
                    🎯 商品详情信息：
                
                🏷️ 商品名称：%s
                🔢 商品ID：%d
                💰 价格：%.2f元
                📝 详细描述：%s
                📊 状态：%s              
                    """,
                        product.getProductName() != null ? product.getProductName() : "未知商品",
                        product.getProductId() != null ? product.getProductId() : 0,
                        product.getPrice() != null ? product.getPrice() : 0.0,
                        product.getDescription() != null ? product.getDescription() : "暂无详细描述",
                        getStatusText(product.getProductStatus())
                ));
            }

            return result.toString();

        } catch (Exception e) {
            log.severe("查询商品时出现错误: " + e.getMessage());
            e.printStackTrace();
            return "查询商品时出现系统错误，请稍后重试。";
        }
    }

    //根据产品名字查询
    @Tool("根据商品名称查询商品")
    public String getProductByName(@P("商品名称") String productName) {
        try {
            log.info("根据名称查询商品，名称: " + productName);

            ResponseEntity<ResponseResult> responseEntity = productApi.getProductsByName(productName);

            if (responseEntity.getStatusCode() != HttpStatus.OK || responseEntity.getBody() == null) {
                return "抱歉，商品服务暂时不可用，请稍后重试。";
            }

            ResponseResult responseResult = responseEntity.getBody();

            if (responseResult.getCode() != 1) {
                return "抱歉，查询商品失败: " + responseResult.getMsg();
            }

            Object data = responseResult.getData();
            ObjectMapper objectMapper = new ObjectMapper();
            ProductDTO product = objectMapper.convertValue(data, ProductDTO.class);

            if (product == null) {
                return "没有找到名称为 " + productName + " 的商品。";
            }

            return String.format("""
                🎯 商品详情信息：
            
                🏷️ 商品名称：%s
                🔢 商品ID：%d
                💰 价格：%.2f元
                📝 详细描述：%s
                📊 状态：%s              
                """,
                product.getProductName() != null ? product.getProductName() : "未知商品",
                product.getProductId() != null ? product.getProductId() : 0,
                product.getPrice() != null ? product.getPrice() : 0.0,
                product.getDescription() != null ? product.getDescription() : "暂无详细描述",
                getStatusText(product.getProductStatus())
            );

        } catch (Exception e) {
            log.severe("根据名称查询商品时出现错误: " + e.getMessage());
            e.printStackTrace();
            return "根据名称查询商品时出现系统错误，请稍后重试。";
        }
    }



    private String getStatusText(Integer status) {
        if (status == null) return "未知";
        switch (status) {
            case 0: return "下架";
            case 1: return "上架";
            default: return "未知状态";
        }
    }



    //=============================轮播图====================
    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class BannerSearchResponse {
        @JsonProperty("data")
        public List<BannerDTO> data;
    }
    @Tool("根据广告轮播图状态查询所有广告轮播图")
    public String getAllBannerByStatus(@P("广告轮播图状态") Integer bannerStatus) {
        try {
            log.info("根据状态查询所有广告轮播图，状态: " + bannerStatus);

            ResponseEntity<ResponseResult> responseEntity = productApi.getBannersByStatus(bannerStatus);

            if (responseEntity.getStatusCode() != HttpStatus.OK || responseEntity.getBody() == null) {
                return "抱歉，广告轮播图服务暂时不可用，请稍后重试。";
            }

            ResponseResult responseResult = responseEntity.getBody();

            if (responseResult.getCode() != 1) {
                return "抱歉，查询商品失败: " + responseResult.getMsg();
            }

            List<?> dataList = (List<?>) responseResult.getData();
            List<BannerDTO> banners = new ArrayList<>();
            ObjectMapper objectMapper = new ObjectMapper();
            for (Object item : dataList) {
                // 将LinkedHashMap转换为BannerDTO对象
                BannerDTO banner = objectMapper.convertValue(item, BannerDTO.class);
                banners.add(banner);
            }

            if (banners == null || banners.isEmpty()) {
                return "目前没有" + getStatusText(bannerStatus) + "的广告轮播图。";
            }

            StringBuilder result = new StringBuilder();
            result.append("为您找到以下").append(getStatusText(bannerStatus)).append("广告轮播图：\n\n");

            for (BannerDTO banner : banners) {
                result.append(String.format("""
                    🎯 广告轮播图详情信息：
                
                🏷️ 广告轮播图名称：%s
                🔢 广告轮播图ID：%d
                📊 广告轮播图状态：%s              
                """,
                        banner.getTitle() != null ? banner.getTitle() : "未知广告轮播图",
                        banner.getBannerId() != null ? banner.getBannerId() : 0,
                        getStatusText(banner.getBannerStatus())
                ));
            }

            return result.toString();

        } catch (Exception e) {
            log.severe("查询商品时出现错误: " + e.getMessage());
            e.printStackTrace();
            return "查询商品时出现系统错误，请稍后重试。";
        }
    }

    //=============================红包福利====================
    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class RedPacketActivitySearchResponse {
        @JsonProperty("data")
        public RedPacketActivityDTO data;
    }
    @Tool("查询最新的红包福利活动信息")
    public String getRedPacketActivity() {
        try {
            log.info("查询最新的红包福利活动信息");

            ResponseEntity<ResponseResult> responseEntity = productApi.getRedPacketActivity();

            if (responseEntity.getStatusCode() != HttpStatus.OK || responseEntity.getBody() == null) {
                return "抱歉，红包福利服务暂时不可用，请稍后重试。";
            }

            ResponseResult responseResult = responseEntity.getBody();

            if (responseResult.getCode() != 1) {
                return "抱歉，查询红包福利失败: " + responseResult.getMsg();
            }

//            RedPacketActivityDTO redPacketActivity = (RedPacketActivityDTO) responseResult.getData();
//            Object data = responseResult.getData();
//            ObjectMapper objectMapper = new ObjectMapper();
//            RedPacketActivityDTO redPacketActivity = objectMapper.convertValue(data, RedPacketActivityDTO.class);

            Object data = responseResult.getData();
            ObjectMapper objectMapper = new ObjectMapper()
                    .registerModule(new JavaTimeModule()); // Register Java 8 date/time module
            RedPacketActivityDTO redPacketActivity = objectMapper.convertValue(data, RedPacketActivityDTO.class);

            if (redPacketActivity == null) {
                return "目前没有最新的红包福利活动。";
            }

            return String.format("""
                🎯 红包福利活动详情信息：
            
                🏷️ 活动标题：%s
                💰 总金额：%.2f元
                🔢 总数量：%d
                ⏰ 活动时间：%s 至 %s
                """,
                redPacketActivity.getTitle() != null ? redPacketActivity.getTitle() : "未知活动",
                redPacketActivity.getTotalAmount() != null ? redPacketActivity.getTotalAmount() : 0.0,
                redPacketActivity.getTotalPackets() != null ? redPacketActivity.getTotalPackets() : 0,
                redPacketActivity.getStartTime() != null ? redPacketActivity.getStartTime().toString() : "未知开始时间",
                redPacketActivity.getEndTime() != null ? redPacketActivity.getEndTime().toString() : "未知结束时间"
            );
        } catch (Exception e) {
            log.severe("查询红包福利活动时出现错误: " + e.getMessage());
            e.printStackTrace();
            return "查询红包福利活动时出现系统错误，请稍后重试。";
        }
    }
}